<template>
  <div class="demand-page-box">
    <div class="page-container">
      <!-- 检索条件 -->
      <div class="form-parent-newbox1">
        <div class="form-title-area">
          <div class="form-title-left-area">
            <span>查询条件</span>
          </div>
          <div class="form-title-right-area">
            <el-button size="mini" icon="el-icon-search" type="primary" @click="handleQuery">查询</el-button>
            <el-button size="mini" icon="el-icon-refresh" type="primary" @click="handleReset">重置</el-button>
          </div>
        </div>
        <el-form size="mini" class="form-area-box" :inline="true" :model="formData" label-position="left">
          <el-row>
            <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="6">
              <el-form-item label="姓名">
                <el-input v-model="formData.name" placeholder="请输入" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="6">
              <el-form-item label="身份证">
                <el-input v-model="formData.sfz" placeholder="请输入" clearable maxlength="18"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="6">
              <el-form-item label="行政区">
                <el-select filterable clearable placeholder="请选择" v-model="formData.districtCode" @change="handleGetHsjcdList">
                  <el-option v-for="item in districtCodeList" :key="item.code" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="6">
              <el-form-item label="核酸检测点">
                <el-select filterable clearable placeholder="请选择" v-model="formData.hsjcd">
                  <el-option v-for="item in hsjcdList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="6">
              <el-form-item label="检测日期">
                <el-date-picker type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" clearable placeholder="请选择" v-model="formData.hsjcDate" value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="6">
              <el-form-item label="检测结果">
                <el-select filterable clearable placeholder="请选择" v-model="formData.hsjcjg">
                  <el-option v-for="item in hsjcDicts" :key="item.code" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="6">
              <el-form-item label="症状分类">
                <el-select filterable clearable placeholder="请选择" v-model="formData.status">
                  <el-option v-for="item in statusDicts" :key="item.code" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="6">
              <el-form-item label="报告上传日期">
                <el-date-picker type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" clearable placeholder="请选择" v-model="formData.reportDate" value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 表格 -->
      <div class="table-buttons-box">
        <el-button v-if="myRole == 'hsjcdManager'" size="mini" type="primary" icon="el-icon-plus" @click="handleAddHsjc">添加</el-button>
      </div>
      <el-table ref="tb" :data="tableData" tooltip-effect="dark" style="width: 100%" :height="tableHeight" border :header-cell-style="{
            background: '#FAFAFA',
            color: '#262626',
            textAlign: 'center',
          }" highlight-current-row>
        <el-table-column align="center" width="50" label="序号" type="index" :index="indexMethod"></el-table-column>
        <el-table-column align="center" prop="name" label="姓名" min-width="80"></el-table-column>
        <el-table-column align="center" prop="sfz" label="身份证" min-width="140" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" prop="jianceTimeShow" label="检测时间" min-width="100"></el-table-column>
        <el-table-column align="center" prop="districtName" label="行政区" min-width="80"></el-table-column>
        <el-table-column align="center" prop="jcdName" label="检测点" min-width="80"></el-table-column>
        <el-table-column align="center" label="检测结果" min-width="80">
          <template slot-scope="scope">
            <el-select v-if="myRole == 'hsjcResultManager'" filterable clearable placeholder="请选择" v-model="scope.row.jcResultCode" @change="handleJcResultChange(scope.row)">
              <el-option v-for="item in hsjcDicts" :key="item.code" :label="item.name" :value="item.code"></el-option>
            </el-select>
            <span v-else>{{scope.row.jcResultName || ""}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="reportTimeShow" label="报告上传时间" min-width="100"></el-table-column>
        <el-table-column align="center" label="症状分类" min-width="80">
          <template slot-scope="scope">
            <el-select v-if="scope.row.jcResultCode == 'yang' && myRole == 'doctor'" filterable clearable placeholder="请选择" v-model="scope.row.status" @change="handleStatusChange(scope.row)">
              <el-option v-for="item in statusDicts" :key="item.code" :label="item.name" :value="item.code"></el-option>
            </el-select>
            <span v-else>{{scope.row.jcResultCode == 'yin' ? "/" : scope.row.statusName ? scope.row.statusName : ""}}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" prop="remark" label="备注" min-width="140" show-overflow-tooltip></el-table-column>
        <el-table-column v-if="myRole == 'hsjcdManager'" fixed="right" align="center" label="操作" width="150">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleUpdateHsjc(scope.row)">修改</el-button>
            <el-button size="mini" type="text" @click="handleDeleteHsjc(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" :totalCount="totalCount" :currentPage="currentPage" :pageSizeList="pageSizeList" :pageSize="pageSize" class="pagination-area-box"></Pagination>
    </div>
    <!-- 新增/编辑用户 弹框 -->
    <el-dialog :title="showCreateHsjcTKTitle" width="80%" :append-to-body="true" :visible.sync="showCreateHsjcTK" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form label-width="100px" label-position="left" :model="hsjcInfo" :rules="rules" ref="createHsjcInfo">
        <el-form-item label="姓名" prop="name">
          <el-input type="text" v-model="hsjcInfo.name" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="身份证" prop="sfz">
          <el-input type="text" v-model="hsjcInfo.sfz" placeholder="请输入" maxlength="18"></el-input>
        </el-form-item>
        <el-form-item label="行政区" prop="districtCode">
          <el-select filterable clearable placeholder="请选择" v-model="hsjcInfo.districtCode" @change="handleGetJcdListByDistrict">
            <el-option v-for="item in districtCodeList" :key="item.code" :label="item.name" :value="item.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="核酸检测点" prop="hsjcd">
          <el-select filterable clearable placeholder="请选择" v-model="hsjcInfo.hsjcd">
            <el-option v-for="item in districtHsjcdList" :key="item.code" :label="item.name" :value="item.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" :rows="4" v-model="hsjcInfo.remark" placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" icon="el-icon-close" @click="showCreateHsjcTK = false">取消</el-button>
        <el-button size="mini" icon="el-icon-check" type="primary" @click="handleSave">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>
  <script>
let me;
import Pagination from "@/components/common/pagination";
import publicFunc from "@/resources/js/publicFunc";
import {
  hsjcList,
  deleteHsjc,
  addHsjc,
  updateHsjc,
  updateHsjcResult,
  updateHsjcStatus,
  getHsjcDicts,
  getHsjcdDicts,
} from "@/api/fangyiData/hsjc.api";
import { getMyDistrictList, } from "@/api/fangyiData/bingli.api";
import { queryLoginuserRole } from "@/api/login.api"
export default {
  data() {
    return {
      publicFunc: publicFunc,
      myRole: "",// 当前登录人的角色
      districtCodeList: [],
      hsjcdList: [],// 核酸检测点列表
      hsjcDicts: [],// 核酸检测结果的字典列表
      statusDicts: [],// 核酸检测后症状类型分类的字典
      // 表单
      formData: {
        name: "",
        sfz: "",
        districtCode: "",
        hsjcd: "",
        hsjcjg: "",
        status: "",
        hsjcDate: [],
        reportDate: [],
      },
      // 表格和分页
      tableHeight: "74vh",
      tableData: [],
      totalCount: 0,
      currentPage: 1,
      pageSizeList: [10, 20, 50],
      pageSize: 10,
      showCreateHsjcTKTitle: "",
      showCreateHsjcTK: false,
      // 修改和添加核酸检测者的基本信息
      districtHsjcdList: [],
      hsjcInfo: {
        id: "",
        name: "",
        sfz: "",
        districtCode: "",
        hsjcd: "",
        remark: "",
      },
      rules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        sfz: [{ required: true, message: "请输入身份证号码", trigger: "blur" }],
        districtCode: [{ required: true, message: "请选择行政区", trigger: "change" }],
        hsjcd: [{ required: true, message: "请选择核酸检测点", trigger: "change" }],
      },
    };
  },
  watch: {
    /**
     * 编辑和新增的弹框
     */
    showCreateHsjcTK(data) {
      if (!data) {
        this.districtHsjcdList = [];
      } else {
        this.$nextTick(() => {
          this.$refs.createHsjcInfo.clearValidate();
        })
      }
    },
    /**
     * 角色变化的时候，按钮可能会显示，所以表格高度要重新计算
     */
    myRole(data) {
      console.log("myRole", data);
      this.$nextTick(() => {
        let formHeight = document.querySelector(".form-parent-newbox1");
        let tableButtonHeight = document.querySelector(".table-buttons-box");
        let paginationHeight = document.querySelector(".pagination-area-box");
        this.tableHeight =
          window.innerHeight -
          formHeight.offsetHeight -
          tableButtonHeight.offsetHeight -
          paginationHeight.offsetHeight -
          20 +
          "px";
      });
    }
  },
  components: {
    Pagination,
  },
  mounted() {
    me = this;
    me.queryRole();// 查询当前登录用户的角色
    me.queryHsjcDicts();// 查询核酸结果的字典
    me.queryDistrictList();// 查询行政区的列表
    me.queryItemsList();// 查询自己权限范围内的数据
    me.$nextTick(() => {
      let formHeight = document.querySelector(".form-parent-newbox1");
      let tableButtonHeight = document.querySelector(".table-buttons-box");
      let paginationHeight = document.querySelector(".pagination-area-box");
      me.tableHeight =
        window.innerHeight -
        formHeight.offsetHeight -
        tableButtonHeight.offsetHeight -
        paginationHeight.offsetHeight -
        20 +
        "px";
    });
    window.onresize = function (res) {
      me.$nextTick(() => {
        let formHeight = document.querySelector(".form-parent-newbox1");
        let tableButtonHeight = document.querySelector(".table-buttons-box");
        let paginationHeight = document.querySelector(".pagination-area-box");
        me.tableHeight =
          window.innerHeight -
          formHeight.offsetHeight -
          tableButtonHeight.offsetHeight -
          paginationHeight.offsetHeight -
          20 +
          "px";
      });
    };
  },
  beforeDestroy() {
    window.onresize = function () { };
  },
  methods: {
    /**
     * 查询自己的角色
     * 
     */
    queryRole() {
      queryLoginuserRole({}).then(res => {
        if (res.code == "200" && res.data && Array.isArray(res.data) && res.data.length > 0) {
          me.myRole = res.data[0].role_code;
        } else {
          me.myRole = "";
        }
      }).catch(err => {
        me.myRole = "";
      })
    },
    /**
     * 行政区的列表
     */
    queryDistrictList() {
      getMyDistrictList({})
        .then((res) => {
          if (res.code == "200") {
            me.districtCodeList = res.data;
          } else {
            me.districtCodeList = [];
          }
        })
        .catch((err) => {
          me.districtCodeList = [];
        });
    },
    /**
     * 行政区变化的时候，动态切换查询该区下有哪些检测点
     */
    handleGetHsjcdList(e) {
      me.formData.hsjcd = "";
      me.hsjcdList = [];
      if (!!e) {
        getHsjcdDicts({
          orgCode: e
        }).then(res => {
          if (res.code == "200") {
            me.hsjcdList = res.data;
          } else {
            me.hsjcdList = [];
          }
        }).catch(err => {
          me.hsjcdList = [];
        })
      }
    },
    /**
     * 查询核酸检测结果的字典
     */
    queryHsjcDicts() {
      getHsjcDicts({})
        .then((res) => {
          if (res.code == "200") {
            me.hsjcDicts = res.data.filter(item => {
              return item.type == "hsjcjg"
            });
            me.statusDicts = res.data.filter(item => {
              return item.type == "status" && item.code != "ykf"
            });
          } else {
            me.hsjcDicts = [];
            me.statusDicts = [];
          }
        })
        .catch((err) => {
          me.hsjcDicts = [];
          me.statusDicts = [];
        });
    },
    /**
     * 查询
     */
    handleQuery() {
      me.currentPage = 1;
      me.queryItemsList();
    },
    /**
     * 重置
     */
    handleReset() {
      me.formData.name = "";
      me.formData.sfz = "";
      me.formData.districtCode = "";
      me.formData.hsjcd = "";
      me.formData.hsjcjg = "";
      me.formData.status = "";
      me.formData.hsjcDate = [];
      me.formData.reportDate = [];
      me.hsjcdList = [];
      me.currentPage = 1;
      me.queryItemsList();
    },
    /**
     * 每页展示数量变化时
     */
    handleSizeChange(e) {
      me.pageSize = e;
      me.currentPage = 1;
      me.queryItemsList();
    },
    /**
     * 当前页码变化时
     */
    handleCurrentChange(e) {
      me.currentPage = e;
      me.queryItemsList();
    },
    // 封装查询和导出的参数列表
    getQueryParam() {
      let param = {
        name: me.formData.name,
        sfz: me.formData.sfz,
        districtCode: me.formData.districtCode,
        hsjcd: me.formData.hsjcd,
        hsjcjg: me.formData.hsjcjg,
        status: me.formData.status,
        hsjcDateStart: me.formData.hsjcDate && me.formData.hsjcDate.length == 2 ? me.formData.hsjcDate[0] : "",
        hsjcDateEnd: me.formData.hsjcDate && me.formData.hsjcDate.length == 2 ? me.formData.hsjcDate[1] + " 23:59:59" : "",
        reportDateStart: me.formData.reportDate && me.formData.reportDate.length == 2 ? me.formData.reportDate[0] : "",
        reportDateEnd: me.formData.reportDate && me.formData.reportDate.length == 2 ? me.formData.reportDate[1] + " 23:59:59" : "",
      };
      return param;
    },
    // 查询表格数据
    queryItemsList() {
      let param = {
        size: me.pageSize,
        page: me.currentPage,
        ...me.getQueryParam(),
      };
      var rLoading = me.openLoading();
      hsjcList(param)
        .then((res) => {
          rLoading.close();
          if (res.code == "200") {
            me.tableData = res.data.map(item => {
              return {
                jianceTimeShow: item.jianceTime ? item.jianceTime.split(".000")[0].replace("T", " ") : "",
                reportTimeShow: item.reportTime ? item.reportTime.split(".000")[0].replace("T", " ") : "",
                jcResultName: item.jcResultCode == "yang" ? "阳性" : item.jcResultCode == "yin" ? "阴性" : "",
                ...item
              }
            });
            me.totalCount = res.total;
          } else {
            me.$message.error(res.msg || "查询失败，请稍后再试~");
          }
        })
        .catch((err) => {
          rLoading.close();
          me.$message.error(err.statusText || "对不起，系统繁忙，请稍后再试~");
        });
    },
    //   序号获取
    indexMethod(index) {
      var total = me.pageSize * (me.currentPage - 1);
      return total + index + 1;
    },
    // 添加
    handleAddHsjc() {
      me.hsjcInfo = {
        id: "",
        name: "",
        sfz: "",
        hsjcd: "",
        remark: "",
      };
      me.showCreateHsjcTKTitle = "添加";
      me.showCreateHsjcTK = true;
    },
    // 修改
    handleUpdateHsjc(item) {
      me.handleGetJcdListByDistrict(item.districtCode);
      me.hsjcInfo = {
        id: item.id,
        name: item.name,
        sfz: item.sfz,
        districtCode: item.districtCode,
        hsjcd: item.jcd,
        remark: item.remark,
      };
      me.showCreateHsjcTKTitle = "编辑";
      me.showCreateHsjcTK = true;
    },
    /**
     * 添加时，行政区变化的时候，检测点要根据行政区动态变化查询
     */
    handleGetJcdListByDistrict(e) {
      me.hsjcInfo.hsjcd = "";
      me.districtHsjcdList = [];
      if (!!e) {
        let param = {
          orgCode: e,
          range: "open"
        }
        var rLoading = me.openLoading();
        getHsjcdDicts(param)
          .then((res) => {
            rLoading.close();
            if (res.code == "200") {
              me.districtHsjcdList = res.data;
            } else {
              me.$message.error(res.msg || "查询失败，请稍后再试~");
            }
          })
          .catch((err) => {
            rLoading.close();
            me.$message.error(err.statusText || "对不起，系统繁忙，请稍后再试~");
          });
      }
    },
    // 添加或修改
    handleSave() {
      let errorTip = !me.hsjcInfo.name
        ? "请输入姓名"
        : !me.hsjcInfo.sfz
          ? "请输入身份证号码"
          : !me.hsjcInfo.hsjcd
            ? "请选择核酸检测点" : "";
      if (!!errorTip) {
        me.$message.error(errorTip);
        return;
      }
      let param = {
        name: me.hsjcInfo.name,
        sfz: me.hsjcInfo.sfz,
        districtCode: me.hsjcInfo.districtCode,
        hsjcd: me.hsjcInfo.hsjcd,
        remark: me.hsjcInfo.remark,
      };
      //   判断是新增还是修改，调的接口不同，要不要传id
      if (me.hsjcInfo.id) {
        param.id = me.hsjcInfo.id;
        confirmSave(updateHsjc(param));
      } else {
        confirmSave(addHsjc(param));
      }
      function confirmSave(pro) {
        let rLoading = me.openLoading();
        pro.then((res) => {
          rLoading.close();
          if (res.code == "200") {
            me.showCreateHsjcTK = false;
            me.$message.success("操作成功~");
            me.queryItemsList();
          } else {
            me.$message.error(res.msg || "操作失败，请稍后再试~");
          }
        })
          .catch((err) => {
            rLoading.close();
            me.$message.error(err.statusText || "对不起，系统繁忙，请稍后再试~");
          });
      }
    },
    // 删除核酸检测的数据
    handleDeleteHsjc(item) {
      me.$alert(`您确认删除${item.name}吗？`, "温馨提示", {
        confirmButtonText: "确认",
        callback: (action) => {
          if (action == "confirm") {
            let rLoading = me.openLoading();
            deleteHsjc({
              id: item.id,
            })
              .then((res) => {
                rLoading.close();
                if (res.code == "200") {
                  me.$message.success("已删除~");
                  me.queryItemsList();
                } else {
                  me.$message.error(res.msg || "删除失败，请稍后再试~");
                }
              })
              .catch((err) => {
                rLoading.close();
                me.$message.error(err.statusText || "对不起，系统繁忙，请稍后再试~");
              });
          }
        },
      });
    },
    // 检测结果修改的监听
    handleJcResultChange(item) {
      let rLoading = me.openLoading();
      updateHsjcResult({
        id: item.id,
        result: item.jcResultCode
      })
        .then((res) => {
          rLoading.close();
          if (res.code == "200") {
            me.$message.success("操作成功~");
            me.queryItemsList();
          } else {
            me.$message.error(res.msg || "操作失败，请稍后再试~");
          }
        })
        .catch((err) => {
          rLoading.close();
          me.$message.error(err.statusText || "对不起，系统繁忙，请稍后再试~");
        });
    },
    /**
     * 症状类型修改的监听
     */
    handleStatusChange(item) {
      let rLoading = me.openLoading();
      updateHsjcStatus({
        id: item.id,
        result: item.status
      })
        .then((res) => {
          rLoading.close();
          if (res.code == "200") {
            me.$message.success("操作成功~");
            me.queryItemsList();
          } else {
            me.$message.error(res.msg || "操作失败，请稍后再试~");
          }
        })
        .catch((err) => {
          rLoading.close();
          me.$message.error(err.statusText || "对不起，系统繁忙，请稍后再试~");
        });
    },
  },
};
  </script>
  <style lang="less" scoped>
.page-container {
  .el-form {
    /deep/.el-col {
      .el-form-item {
        .el-form-item__label {
          width: 100px;
        }
        .el-form-item__content {
          width: calc(100% - 110px);
        }
      }
    }
    .el-button--primary {
      color: #fff;
    }
  }
  /deep/.el-table {
    .el-table__body {
      .el-table__row {
        .el-table__cell {
          .el-select {
            font-size: 12px;
            .el-input {
              font-size: 12px;
            }
          }
        }
      }
    }
  }
}

/deep/.el-dialog {
  .el-dialog__body {
    max-height: 60vh;
    overflow: auto;
    .el-form {
      .el-form-item {
        margin-top: 1.2em;
        .el-form-item__content {
          .el-select {
            width: 100%;
          }
        }
      }
    }
  }
}
</style>
  